package utils;

import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.sql.*;
import java.util.Properties;


/*
 * JDBC 工具类
 * 
 */
public class JDBCUtils {
	
	
	/*
	 * 连接数据库步骤
	 * 1. 加载驱动
	 * 2. 获取连接对象 connection
	 * 3. 编写sql语句
	 * 4. 获取执行对象 preparedStatement
	 * 5. 执行sql语句 如果sql语句是一个查询的话，使用的方法是executeQuery,如果sql语句是除了查询以外的话，使用的方法是executeUpdate	
	 */
	
	/*
	 * 
	 * 1. 加载配置文件
	 * 2. 获取配置文件的值
	 * 3. 加载驱动
	 */
	
	static Connection connection = null;
	static String driver = null;
	static String url = null;
	static String user = null;
	static String password = null;
	
	static {
		try {
		// 1. 加载配置文件
		Properties pro = new Properties();
		ClassLoader classLoader = JDBCUtils.class.getClassLoader();
		URL resource = classLoader.getResource("jdbc.properties");
		
		assert resource != null;
		String path = resource.getPath();
		pro.load(new FileReader(path));

		// 2. 获取配置文件的值
		driver = pro.getProperty("driver");
		url = pro.getProperty("url");
		user = pro.getProperty("user");
		password = pro.getProperty("password");
		System.out.println(driver);
		System.out.println(password);
		
		// 3. 加载驱动
		Class.forName(driver);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("获取配置文件出错");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("获取驱动失败	");
		}
	}
	// 1. 获取连接，返回连接对象
	
	public static Connection getConnection() {
		try {
			connection = DriverManager.getConnection(url, user, password);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("连接数据库失败");
		}
		return connection;
	}
	// 2. 关闭连接对象
	public static void close(Connection connection, PreparedStatement pStatement,ResultSet rSet) {
		
		try {
			if(connection != null) {
				connection.close();
			}
			if(connection != null) {
				pStatement.close();
			}
			if(rSet !=null) {
				rSet.close();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("关闭失败1！");
		}

	}
	
public static void close(Connection connection, PreparedStatement pStatement) {
		
		try {
			if(connection != null) {
				connection.close();
			}
			if(connection != null) {
				pStatement.close();
			}
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("关闭失败2！");
		}

	}
}
